package com.example.dayu521.sg_oss.service.stream;

import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class EmitterOPS extends OutputStream {

    private ResponseBodyEmitter rbe;

    private ByteArrayOutputStream byteArrayOutputStream;

    public EmitterOPS(){
        rbe=new ResponseBodyEmitter();
        byteArrayOutputStream=new ByteArrayOutputStream();
    }

    public ResponseBodyEmitter getRbe(){
        return rbe;
    }

    @Override
    public void write(int b) throws IOException {
        byteArrayOutputStream.write(b);
        if(byteArrayOutputStream.size()>1024*8){
            rbe.send(byteArrayOutputStream.toByteArray());
            byteArrayOutputStream.reset();
        }
    }

    @Override
    public void write(@NotNull byte[] b) throws IOException {
        byteArrayOutputStream.write(b);
        if(byteArrayOutputStream.size()>1024*8){
            rbe.send(byteArrayOutputStream.toByteArray());
            byteArrayOutputStream.reset();
        }
    }

    @Override
    public void flush() throws IOException {
        byteArrayOutputStream.flush();
        rbe.send(byteArrayOutputStream.toByteArray());
        byteArrayOutputStream.reset();
    }

    @Override
    public void close() throws IOException {
        flush();
        byteArrayOutputStream.close();
        rbe.complete();
    }
}
